package cn.tedu.dbinit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class DbInitApplication {

	@Autowired
	private DataSource dataSource;

	public static void main(String[] args) {
		SpringApplication.run(DbInitApplication.class, args);
	}

	@PostConstruct//等项目完全启动才执行
	public void init() throws Exception {
		exec(dataSource,"sql/account.sql");
		exec(dataSource,"sql/order.sql");
		exec(dataSource,"sql/seata-server.sql");
		exec(dataSource,"sql/storage.sql");
	}

	private void exec(DataSource dataSource , String file) throws Exception {
		ClassPathResource res = new ClassPathResource(file, DbInitApplication.class.getClassLoader());
		EncodedResource eres = new EncodedResource(res, "UTF-8");
		ScriptUtils.executeSqlScript(dataSource.getConnection(),eres);
	}
}
